package common

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"io/ioutil"
	"os"
	"time"
)

type DBJsonConf struct {
	AliasName string
	DBHost    string
	DBUser    string
	DBPwd     string
	DBName    string
}

func InitMysqlDB() error {
	data, err := ioutil.ReadFile("conf/dbconf.json")
	if err != nil {
		return err
	}
	var conf []DBJsonConf
	err = json.Unmarshal(data, &conf)
	if err != nil {
		return err
	}
	for _, v := range conf {
		err = registerMysqlDB(v.AliasName, v.DBUser, v.DBPwd, v.DBHost, v.DBName)
		if err != nil {
			return err
		}
	}
	return nil
}

func registerMysqlDB(aliasName, user, password, host string, dbName string) error {
	orm.RegisterDriver("mysql", orm.DRMySQL)
	//暂时把idleConnection设置为0,为了防止invalid connection发生,把maxOpenConn设置为0
	return orm.RegisterDataBase(aliasName, "mysql",
		fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&loc=Local", user, password, host, dbName), 0, 0)
}

func InitDB() {
	LogPc.Debug("---------------------初始化数据库开始----------------------------------")
	err := InitMysqlDB()
	if err != nil {
		panic("初始化数据库连接失败:" + err.Error())
	}
	if beego.BConfig.RunMode == "dev" {
		LogPc.Debug("---------------------开发模式下开启数据库日志记录----------------------------------")
		orm.Debug = true
		today := time.Now().Format("20060102")
		file, err := os.OpenFile("log/database"+today+"_error.txt", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
		if err != nil {
			panic(fmt.Sprintf("创建打开数据库错误记录文件失败:%v", err))
		}
		orm.DebugLog = orm.NewLog(file)
	} else {
		LogPc.Debug("---------------------生产模式下不开启数据库日志记录----------------------------------")
	}
	LogPc.Debug("---------------------初始化数据库结束----------------------------------")
}
